﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class WarriorManager : MonoBehaviour {
    /// <summary>
    /// 战场中的单位数量
    /// </summary>
    public int SoldierCount;
    /// <summary>
    /// 当单位数量变动超过阈值时，就会重建KD树
    /// </summary>
    public int RebuildKDTreeFrameSpace;
    public Ticker RebuildKDTreeTicker = new Ticker();

    private static WarriorManager instance;
    public static WarriorManager Instance
    {
        get
        {
            return instance;
        }
    }

    public void Awake()
    {
        if (instance == null) instance = this;
        else if (instance != this)
        {
            Destroy(this);
            return;
        }
        RebuildKDTreeTicker = new Ticker(RebuildKDTreeFrameSpace, false);
    }

    public List<Warrior> Soldiers = new List<Warrior>();
    public Dictionary<PlayerType, List<Warrior>> OwnerSoldierListView = new Dictionary<PlayerType, List<Warrior>>();
    public Dictionary<PlayerType, KDTree> OwnerSoldierKdTreeView = new Dictionary<PlayerType, KDTree>();

    private void RealUpdate()
    {
        if(RebuildKDTreeTicker.Tick())
        {
            RebuildKDTree();
        }
    }

    private void Update()
    {
        RealUpdate();
    }


    public void Enroll(Warrior unit)
    {
        SoldierCount++;
        Soldiers.Add(unit);
        if (!OwnerSoldierListView.ContainsKey(unit.unitOwner))
        {
            OwnerSoldierListView.Add(unit.unitOwner, new List<Warrior>());
        }
        OwnerSoldierListView[unit.unitOwner].Add(unit);
    }
    public void Disenroll(Warrior unit)
    {
        SoldierCount--;
        Soldiers.Remove(unit);
        OwnerSoldierListView[unit.unitOwner].Remove(unit);
    }

    public void RebuildKDTree()
    {
        foreach (var v in OwnerSoldierListView)
        {
            if (!OwnerSoldierKdTreeView.ContainsKey(v.Key))
            {
                OwnerSoldierKdTreeView.Add(v.Key, null);
            }
            OwnerSoldierKdTreeView[v.Key] = KDHelper.TreeFromUnitPars(v.Value);
        }
    }

    public Warrior GetNearestUnit(Vector3 position, PlayerType unitOwner)
    {
        Warrior nearestUnit = null;
        if(OwnerSoldierKdTreeView.ContainsKey(unitOwner) && OwnerSoldierKdTreeView[unitOwner]!=null)
        {
            nearestUnit = KDHelper.FindNearestUP(position, OwnerSoldierListView[unitOwner], OwnerSoldierKdTreeView[unitOwner]);
        }
        return nearestUnit;
    }

}
